# import the necessary packages
import io
import random
import uuid
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.applications.resnet50 import preprocess_input
import numpy as np
import redis
import time
from PIL import Image
import json
from Common import settings, helpers


def prepare_image(ima, target):
    # if the image mode is not RGB, convert it
    if ima.mode != "RGB":
        ima = ima.convert("RGB")
    # resize the input image and preprocess it
    ima = ima.resize(target)
    ima = img_to_array(ima)
    ima = np.expand_dims(ima, axis=0)
    ima = preprocess_input(ima)
    # return the processed image
    return ima


# connect to Redis server
db = redis.StrictRedis(host=settings.REDIS_HOST,
                       port=settings.REDIS_PORT, db=settings.REDIS_DB, password=settings.PASSWORD)
# number of AI app in system
appNum = 3
# number of system running periods
NUM_PERIOD = 60
Period = 1.0
lam = 4
IMAGE_PATH = "dog.jpg"
Task_Req_QUEUE = "TaskReq"
# load the input image and construct the payload for the request
imageOrigin = Image.open(io.BytesIO(open(IMAGE_PATH, "rb").read()))
# print(image)
total_task = 0
for period in range(0, NUM_PERIOD):
    NUM_REQUESTS = np.random.poisson(lam=lam)
    total_task += NUM_REQUESTS
    for i in range(0, NUM_REQUESTS):
        appId = random.randint(0, appNum-1)
        # task unique Id
        image = prepare_image(imageOrigin, (settings.IMAGE_WIDTH[appId], settings.IMAGE_HEIGHT[appId]))
        # ensure our NumPy array is C-contiguous as well,
        # otherwise we won't be able to serialize it
        image = image.copy(order="C")
        image = helpers.base64_encode_image(image)
        k = str(uuid.uuid4())
        # print(image)
        taskReq = {"id": k, "data": image, "appId": appId}
        db.lpush(Task_Req_QUEUE, json.dumps(taskReq))
    time.sleep(Period)
print(total_task)
